<!-- 管理员 -->
<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="roleName" label="关键字">
          <el-input
            v-model="queryParams.roleName"
            placeholder="角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="handleOpenDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <!-- <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
        >
          <i-ep-delete />
          批量删除
        </el-button> -->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="roleList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="roleId"
          label="编号"
          align="center"
          prop="roleId"
          width="150"
        />
        <el-table-column
          key="remark"
          label="标识"
          align="center"
          prop="remark"
          width="280"
        />

        <el-table-column
          key="roleName"
          label="角色名称"
          width="280"
          align="center"
          prop="roleName"
        />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.roleStatus === 0" type="success">
              启用
            </el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center">
          <template #default="scope">
            <text>
              {{
                new Date(scope.row.createdAt)
                  .toISOString()
                  .replace("T", " ")
                  .substring(0, 19)
              }}
            </text>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenAssignPermDialog(scope.row)"
            >
              <i-ep-position />
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="标识" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入标识" />
        </el-form-item>
        <el-form-item label="状态" prop="roleStatus">
          <el-radio-group v-model="formData.roleStatus">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-drawer
      v-model="assignPermDialogVisible"
      :title="'【' + checkedRole.name + '】权限分配'"
      size="500"
    >
      <!-- <div class="flex-x-between">
        <el-input
          v-model="permKeywords"
          clearable
          class="w-[200px]"
          placeholder="菜单权限名称"
        >
          <template #prefix>
            <i-ep-search />
          </template>
        </el-input>

        <div class="flex-center">
          <el-button type="primary" size="small" plain @click="togglePermTree">
            <i-ep-switch />
            {{ isExpanded ? "收缩" : "展开" }}
          </el-button>
          <el-checkbox
            v-model="parentChildLinked"
            @change="handleparentChildLinkedChange"
            class="ml-5"
          >
            父子联动
          </el-checkbox>

          <el-tooltip placement="bottom">
            <template #content>
              如果只需勾选菜单权限，不需要勾选子菜单或者按钮权限，请关闭父子联动
            </template>
            <i-ep-QuestionFilled
              class="ml-1 color-[--el-color-primary] inline-block cursor-pointer"
            />
          </el-tooltip>
        </div>
      </div> -->

      <el-tree
        ref="permTreeRef"
        node-key="menuId"
        show-checkbox
        :data="menuPermOptions"
        :default-expand-all="true"
        :check-strictly="!parentChildLinked"
        class="mt-5"
        :default-checked-keys="checkedMenuIds"
        :props="defaultProps"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAssignPermSubmit">
            确 定
          </el-button>
          <el-button @click="assignPermDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Roles",
  inheritAttrs: false,
});
import rolesAPI, { RolesVO, RplesPageQuery, RolesForm } from "@/api/role";
import menuAPI, { MenuVO } from "@/api/menu";
import { AxiosResponse } from "axios";

const queryFormRef = ref(ElForm);
const roleFormRef = ref(ElForm);
const permTreeRef = ref<InstanceType<typeof ElTree>>();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const defaultProps = {
  children: "children",
  label: "menuName",
};
const checkedMenuIds = ref<any>([]);

const queryParams = reactive<RplesPageQuery>({
  current: 1,
  pageSize: 10,
  roleName: "",
});

// 角色表格数据
const roleList = ref<any>([]);
// 菜单权限下拉
const menuPermOptions = ref<MenuVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
// 角色表单
const formData = reactive<RolesForm>({
  roleId: undefined,
  roleName: "",
  roleStatus: undefined,
  remark: "",
});

const rules = reactive({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  remark: [{ required: true, message: "请输入标识", trigger: "blur" }],
});

// 选中的角色
interface CheckedRole {
  id?: number;
  name?: string;
}
const checkedRole = ref<CheckedRole>({});
const assignPermDialogVisible = ref(false);

const permKeywords = ref("");
const isExpanded = ref(true);

const parentChildLinked = ref(true);

/** 查询 */
function handleQuery() {
  loading.value = true;
  rolesAPI
    .getRoles(queryParams.roleName)
    .then((data) => {
      // console.log(data, "角色列表");
      roleList.value = data;
      total.value = data.length;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.current = 1;
  queryParams.roleName = "";
  checkedMenuIds.value = [];
  handleQuery();
}

/** 打开角色弹窗 */
function handleOpenDialog(role?: any) {
  dialog.visible = true;
  if (role) {
    dialog.title = "修改角色";
    Object.assign(formData, role);
  } else {
    dialog.title = "新增角色";
  }
}

/** 提交角色表单 */
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.roleId;
      console.log(roleId, "roleId");
      if (roleId) {
        rolesAPI
          .updateRoles(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        rolesAPI
          .updateRoles(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭角色弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  formData.roleId = undefined;
  formData.roleStatus = undefined;
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 删除角色 */
function handleDelete(role?: any) {
  console.log(role, "删除内容");
  const roleIds = [role.roleId || ids.value].join(",");
  console.log(roleIds, "删除内容id");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      rolesAPI
        .deleteRoles(roleIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 打开分配菜单权限弹窗 */
async function handleOpenAssignPermDialog(row: RolesVO) {
  const roleId = row.roleId;
  if (roleId) {
    assignPermDialogVisible.value = true;
    loading.value = true;

    checkedRole.value.id = roleId;
    checkedRole.value.name = row.roleName;

    // 获取所有的菜单
    menuPermOptions.value = await menuAPI.getMenu();
    // 回显角色已拥有的菜单
    rolesAPI
      .getRolesMenu(roleId)
      .then((data) => {
        checkedMenuIds.value = data;
      })
      .finally(() => {
        loading.value = false;
      });
  }
}
/** 分配菜单权限提交 */
function handleAssignPermSubmit() {
  const roleId = checkedRole.value.id;
  if (roleId) {
    const checkedMenuIds: number[] = permTreeRef
      .value!.getCheckedNodes(false, true)
      .map((node: any) => node.value);
    const menuIds = permTreeRef?.value?.getCheckedKeys();
    // const menuIdsOther = permTreeRef?.value?.getHalfCheckedKeys();
    // let menuList = ref<any>([]);
    // if (menuIds && menuIdsOther) {
    //   menuList.value = menuIds.concat(menuIdsOther);
    // }
    loading.value = true;
    rolesAPI
      .undateRolesMenu(roleId, { mendIds: menuIds })
      .then(() => {
        ElMessage.success("分配权限成功");
        assignPermDialogVisible.value = false;
        handleResetQuery();
      })
      .finally(() => {
        loading.value = false;
      });
  }
}

/** 展开/收缩 菜单权限树  */
function togglePermTree() {
  isExpanded.value = !isExpanded.value;
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
      if (isExpanded.value) {
        node.expand();
      } else {
        node.collapse();
      }
    });
  }
}

/** 权限筛选 */
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val);
});

function handlePermFilter(
  value: string,
  data: {
    [key: string]: any;
  }
) {
  console.log(data, value, "datavalue");
  if (!value) return true;
  return data.menuId.includes(value);
}

/** 父子菜单节点是否联动 change*/
function handleparentChildLinkedChange(val: any) {
  parentChildLinked.value = val;
}

onMounted(() => {
  handleQuery();
  /** 角色分配权限   组件tree树需要的id */
  // let list: any = [];
  // function computMenus(all: any, req: any) {
  //   all.forEach((item) => {
  //     req.forEach((val) => {
  //       if (item.menuId === val.menuId) {
  //         if (
  //           item.children.length === val.children.length &&
  //           item.children &&
  //           val.children
  //         ) {
  //           list.push(item.menuId);
  //           computMenus(item.children, val.children);
  //         } else if (
  //           item.children &&
  //           val.children &&
  //           item.children.length !== val.children.length
  //         ) {
  //           computMenus(item.children, val.children);
  //         } else {
  //           return false;
  //         }
  //       }
  //     });
  //   });
  // }
  // computMenus(originalData, requestedData);
  // console.log(list, "计算之后的数组");
});
</script>
